package com.dc.event.listener.impl;

import java.util.ArrayList;
import java.util.List;

import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryListener;

import com.dc.event.Const;
import com.dc.event.config.ConfigFactory;
import com.dc.event.config.ListenerConfig;
import com.dc.event.config.impl.DefaultConfigFactory;
import com.dc.event.listener.ListenersFactory;
import com.dc.event.listener.SipJobListener;

public class DefaultListenersFactory implements ListenersFactory {
	private static ListenersFactory jobListenersFactory = new DefaultListenersFactory(new DefaultConfigFactory(Const.CONFIG_FILE_PATH));
	List<ListenerConfig<SipJobListener>> jobListenerConfigs;
	List<ListenerConfig<JobEntryListener>> jobEntryListenerConfigs;
	/**
	 * 
	 * <p>Title: </p>
	 * <p>Description: </p>
	 * @param jobConfigFactory
	 * @throws Exception
	 */
	public DefaultListenersFactory(ConfigFactory jobConfigFactory){
		try {
			jobListenerConfigs = jobConfigFactory.createJobListenerConfigs();
			jobEntryListenerConfigs = jobConfigFactory.createJobEntryListenerConfigs();
		} catch (Exception e) {
			throw new RuntimeException("init DefaultJobListenersFactory has error:",e);
		}		
	};
	@Override
	public List<JobEntryListener> createJobEntryListeners(Job job) {
		List<JobEntryListener> JobEntryListeners = new ArrayList<JobEntryListener>(jobListenerConfigs.size());
		try {
			for (ListenerConfig<JobEntryListener> jobEntryListenerConfig : jobEntryListenerConfigs) {
				if (jobEntryListenerConfig.getListenerParam(Const.JOBNAME) != null
						&& !jobEntryListenerConfig.getListenerParam(
								Const.JOBNAME).equals(job.getJobname())) {
					continue;
				}
				JobEntryListeners.add(jobEntryListenerConfig.getListenerClass()
						.newInstance());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		return JobEntryListeners;
	}

	@Override
	public List<SipJobListener> createSipJobListeners(Job job) {
		List<SipJobListener> sipJobListeners = new ArrayList<SipJobListener>(jobListenerConfigs.size());
		try {
			for (ListenerConfig<SipJobListener> jobListenerConfig : jobListenerConfigs) {
				if (jobListenerConfig.getListenerParam(Const.JOBNAME) != null
						&& !jobListenerConfig.getListenerParam(
								Const.JOBNAME).equals(job.getJobname())) {
					continue;
				}
				sipJobListeners.add(jobListenerConfig.getListenerClass().newInstance());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return sipJobListeners;
	}
	public List<ListenerConfig<SipJobListener>> getJobListenerConfigs() {
		return jobListenerConfigs;
	}
	public List<ListenerConfig<JobEntryListener>> getJobEntryListenerConfigs() {
		return jobEntryListenerConfigs;
	}
	public static ListenersFactory getInstance(){
		return jobListenersFactory;
	}
}
